//
//  DataBaseHandler.m
//  UI19_数据库
//
//  Created by 刘宇文 on 14-12-8.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "DataBaseHandler.h"

@interface DataBaseHandler ()

@property (nonatomic, retain) UIAlertView *alertView;

@end

@implementation DataBaseHandler


+ (DataBaseHandler *)shareInstance
{
    // 当第一次执行的时候会产生一个空指针
    static DataBaseHandler *handler = nil;
    
    // 对指针进行判断, 当第一次执行的时候创建一个对象
    if (handler == nil) {
        // 单例不需要release
        handler = [[DataBaseHandler alloc] init];
        
    }
    // 无论是创建的和已经存在的, 都在这里直接return出去
    return handler;
    
}


- (BOOL)openDB:(NSString *)uid
{
    // 打开数据库
    
    // 1.拼接一个数据库文件路径
    
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *folderPath = [docPath stringByAppendingFormat:@"/%@", uid];
    [fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];
    NSString *dbPath  = [folderPath stringByAppendingPathComponent:@"Album.db"];
//    NSLog(@"%@", dbPath);
    
    
    
    // 参数1: 数据库文件存储的路径
    // 参数2: 数据库dbpoint指针地址
    // 返回值: 执行sqlite函数的结果(int类型)
    int result = sqlite3_open([dbPath UTF8String], &dbPoint);
    
    
    return [self judgeResult:result text:@"打开"];
    
    
//    NSLog(@"打开数据库结果: %d", result);
//    NSLog(@"数据库文件路径: %@", dbPath);
    
//    return YES;
}

- (BOOL)confirmResult:(int)result text:(NSString *)text
{
    if (result == SQLITE_OK) {
        
        NSLog(@"%@成功", text);
        
        self.alertView = [[UIAlertView alloc] initWithTitle:@"收藏成功" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [self.alertView show];
        [_alertView release];
        
        [self timing];
        return YES;
    }else {
        NSLog(@"错误编码: %d", result);
        NSLog(@"%@失败", text);
        
        self.alertView = [[UIAlertView alloc] initWithTitle:@"已收藏" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [self.alertView show];
        [_alertView release];
        
        [self timing];
        return NO;
    }
    
    
}



- (BOOL)closeDB
{
    int result = sqlite3_close(dbPoint);

    return [self judgeResult:result text:@"关闭"];
}

- (BOOL)judgeResult:(int)result text:(NSString *)text
{
    if (result == SQLITE_OK) {
        
        NSLog(@"%@成功", text);

        return YES;
    }else {
        NSLog(@"错误编码: %d", result);
        NSLog(@"%@失败", text);
        
        return NO;
    }
}

- (void)timing
{
    [NSTimer scheduledTimerWithTimeInterval:0.8f
                                     target:self
                                   selector:@selector(dismissAlert:)
                                   userInfo:nil
                                    repeats:NO];
}

- (void)dismissAlert:(NSTimer *)timer{
    
    
    [self.alertView dismissWithClickedButtonIndex:0 animated:YES];
    
}

// 创建表
- (BOOL)createTable
{
    // SQL语句
    NSString *sql = @"create table album(albumTitle text, albumId text primary key)";
    
    // 执行SQL语句的函数
    // 参数1: 数据库指针
    // 参数2: SQL语句
    int result = sqlite3_exec(dbPoint, [sql UTF8String], NULL, NULL, NULL);
    
    return [self judgeResult:result text:@"创建表"];
    
}
// 添加数据
- (BOOL)insertString:(Album *)tracks
{
    // 拼接SQL语句的时候注意: 字符串要以单引号(')标记
    NSString *sql = [NSString stringWithFormat:@"insert into album values('%@','%@')", tracks.title, [tracks.albumId description]];

    int result = sqlite3_exec(dbPoint, [sql UTF8String], NULL, NULL, NULL);

    return [self confirmResult:result text:@"数据添加"];
  
}

// 查询数据
- (NSMutableArray *)seleteAll
{
    // 1. 创建一个数据库的替身, 存储对数据库的所有操作
    
    sqlite3_stmt *stmt = nil;
    
    // 2. 准备SQL语句并执行, 将结果保存在stmt中
    
    NSString *sql = @"select * from album";
    
    // 参数1: 数据库指针
    // 参数2: SQL语句
    // 参数3: 限制SQL语句的长度(如果是-1, 就是不限制)
    // 参数4: 替身指针的地址
    // 作用: 让数据库执行SQL语句, 并把结果保存到stmt中
    int result = sqlite3_prepare_v2(dbPoint, [sql UTF8String], -1, &stmt, NULL);
    
    
    // 3. 创建一个可变数组, 用于存储数据
    
    NSMutableArray *stuArr = [NSMutableArray array];
    
    // 4. 取遍历所有的数据, 创建相应的学生对象
    
    if (result == SQLITE_OK) {
        
        // 当SQL执行成功, 遍历数据
        // 循环遍历所有的结果, 每次遍历到一条数据, 都会返回SQLITE_ROW; 如果没有数据了, 就不会返回SQLITE_ROW, 跳出循环
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            
            // 再循环中去按列取数据
            
            // text类型的数据取法
            
            const unsigned char *albumTitle = sqlite3_column_text(stmt, 0);
            
            // 将char *转为NSString字符串
            
            NSString *titleName = [NSString stringWithUTF8String:(const char *)albumTitle];
            
            // 取address数据
            
            const unsigned char *albumId = sqlite3_column_text(stmt, 1);
            
            NSString *add = [NSString stringWithUTF8String:(const char *)albumId];
            
            NSNumber *number = [NSNumber numberWithFloat:[add floatValue]];
            
            
            Album *album = [[Album alloc] init];
            
            album.title = titleName;
            
            album.albumId = number;
            
            
            // 将学生对象添加到数组中
            [stuArr addObject:album];
            [album release];
        }
        
    }
    // 销毁stmt替身, 把里面的操作和结果写入本地sqlite文件
    sqlite3_finalize(stmt);
    
    return stuArr;
}

//// 修改数据
//- (BOOL)updateString:(Activity *)activity withName:(NSString *)newName
//{
//    NSString *sql = [NSString stringWithFormat:@"update activity set name = '%@' where name = '%@'", newName, activity.title];
//    
//    int result = sqlite3_exec(dbPoint, [sql UTF8String], NULL, NULL, NULL);
//    
//    return [self judgeResult:result text:@"数据修改"];
//}

// 删除数据
//- (BOOL)deleteStudent
//{
//    NSString *sql = [NSString stringWithFormat:@"delete from activity"];
//    
//    int result = sqlite3_exec(dbPoint, [sql UTF8String], NULL, NULL, NULL);
//    
//    return [self judgeResult:result text:@"数据删除"];
//    
//}
//
- (BOOL)deleteTitle:(NSString *)title
{
    NSString *sql = [NSString stringWithFormat:@"delete from album where albumTitle = '%@'", title];
//    NSLog(@"%@", sql);
    int result = sqlite3_exec(dbPoint, [sql UTF8String], NULL, NULL, NULL);
    
    
    return [self judgeResult:result text:@"数据删除"];
}



@end
